﻿using CsvHelper;
using CsvHelper.Configuration;
using DataWorks_Tools.MappModals;
using DataWorks_Tools.MappModals.CalSaveModals;
using System.Collections.Generic;
using System.Formats.Asn1;
using System.Globalization;
using System.Reflection.PortableExecutable;
using System.Text;
using static DataWorks_Tools.BasicMethods.ReadfromCSV;

namespace DataWorks_Tools.BasicMethods
{
    public static class CSVHelperClass
    {
        private const double interval500hz = 0.002;

        /// <summary>
        /// 获得第一个csv的标题行
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string[] GetHeader(string filePath)
        {
            using (var reader = new StreamReader(filePath, Encoding.UTF8))
            using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)))
            {
                csv.Read();
                csv.ReadHeader();
                return csv.HeaderRecord;
            }
        }
        /// <summary>
        /// 获得csv文件的标题数量
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static int GetHeaderCount(this string filePath)
        {
            var t=GetHeader(filePath);
            return t.Length;
        }



        /// <summary>
        /// 读取某个csv，并写入到另一个csv，不包含标题行
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="csvWriter"></param>
        static void WriteData(string filePath, CsvWriter csvWriter,int fileindex)
        {
            using (var reader = new StreamReader(filePath, Encoding.UTF8))
            using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)))
            {
                csv.Read();
                csv.ReadHeader();
                int row = 0;
                while (csv.Read())
                {
                    var records = csv.GetRecord<dynamic>();
                    if(fileindex == 0)
                    {
                        csvWriter.WriteRecord(records);
                    }
                    else
                    {
                        foreach (var record in records)
                        {
                            if (string.Equals(record.Key, "Time", StringComparison.OrdinalIgnoreCase))
                            {
                                csvWriter.WriteField(5 * fileindex + (row * interval500hz));
                            }
                            else
                            {
                                csvWriter.WriteField(record.Value);
                            }
                        }
                    }
                    row++;
                    csvWriter.NextRecord();

                }
            }
        }

        static  void WriteDataBasic(string filePath, CsvWriter csvWriter, int fileindex, int startrow, int endrow, int filecount,int rowcount,int sumcount)
        {
            using (var reader = new StreamReader(filePath, Encoding.UTF8))
            using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)))
            {
                csv.Read();
                csv.ReadHeader();
                int row = 0;
                while (csv.Read())
                {
                    row++;
                    //判断是否第一个文件
                    if (fileindex == 0)
                    {
                        //起始行若不为0，则到了起始行再读取
                        if (row >= startrow)
                        {
                            var record = csv.GetRecord<dynamic>();
                            foreach (var r in record)
                            {
                                //忽略大小写
                                if (string.Equals(r.Key, "Time", StringComparison.OrdinalIgnoreCase))
                                {
                                    csvWriter.WriteField(interval500hz * (startrow==0? (row - startrow-1) : (row - startrow)));
                                }
                                else
                                {
                                    csvWriter.WriteField(r.Value);
                                }
                                
                            }
                            //这个特别重要，意思是重启下一行，放的位置很关键，不能放错位置
                            csvWriter.NextRecord();
                        }
                       
                    }
                    //如果是最后一个文件
                    else if (fileindex == filecount - 1)
                    {
                        if (row <= endrow || endrow == 0)
                        {
                            var record = csv.GetRecord<dynamic>();
                            foreach (var r in record)
                            {
                                if (string.Equals(r.Key, "Time", StringComparison.OrdinalIgnoreCase))
                                {
                                    csvWriter.WriteField(interval500hz * (rowcount - startrow + row) + interval500hz * (sumcount-rowcount));
                                }
                                else
                                {
                                    csvWriter.WriteField(r.Value);
                                }
                            }
                            csvWriter.NextRecord();
                        }
                    }
                    //读取的是中间的文件，肯定是全部行数读取
                    else
                    {
                        var records = csv.GetRecord<dynamic>();
                        foreach (var record in records)
                        {
                            if (string.Equals(record.Key, "Time", StringComparison.OrdinalIgnoreCase))
                            {
                                csvWriter.WriteField(interval500hz * (rowcount - startrow + row) + interval500hz * (sumcount - rowcount));
                            }
                            else
                            {
                                csvWriter.WriteField(record.Value);
                            }
                        }
                        csvWriter.NextRecord();
                    }
                   
                }
                
            }
        }

        /// <summary>
        /// 利用csvhelper来读取特定列号的数据
        /// </summary>
        /// <param name="file"></param>
        /// <param name="idx"></param>
        /// <returns></returns>
        public static List<double> GetDataFromColumnIdx(this FileInfo file, int idx)
        {
            List<double> data = new List<double>();
            // 先检查文件是否存在和非空  
            if (!file.Exists || file.Length == 0)
            {
                return data;  // 如果文件不存在或为空，直接返回空列表  
            }
            using (var reader = new StreamReader(file.FullName, Encoding.UTF8))
            using (var csvReader = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)))
            {
                if (!csvReader.Read() || !csvReader.ReadHeader()) // 确保有读取到数据和标题  
                {
                    return data;  // 如果没有读取到任何数据或标题，也返回空列表  
                }
                while (csvReader.Read())
                {
                    var value = csvReader.GetField<double>(idx);
                    data.Add(value);
                }
            }
            return data;
        }

        //利用csvhelper来读取特定列名的数据,这里会有问题，如果文件里没有数据，就会出错
        public static List<double> GetDataFromColumnName(this FileInfo file, string name)
        {
            List<double> data = new List<double>();
            // 先检查文件是否存在和非空  
            if (!file.Exists || file.Length == 0)
            {
                return data;  // 如果文件不存在或为空，直接返回空列表  
            }
            using (var reader = new StreamReader(file.FullName, Encoding.UTF8))
            using (var csvReader = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)))
            {
                if (!csvReader.Read() || !csvReader.ReadHeader()) // 确保有读取到数据和标题  
                {
                    return data;  // 如果没有读取到任何数据或标题，也返回空列表  
                }
                while (csvReader.Read())
                {
                    var records = csvReader.GetRecord<dynamic>();
                    foreach (var record in records)
                    {
                        if (record.Key.ToLower() == name.ToLower())
                        {
                            var t=Double.TryParse(record.Value,out double value);
                            if (t)
                            {
                                data.Add(value);
                            }
                        }
                    }
                }
            }
            return data;
        }

        /// <summary>
        /// 一次性的读取csv到List<string>
        /// </summary>
        /// <param name="fileInfo">FileInfo文件类</param>
        /// <returns>List<string></returns>
        public static async Task<List<string>> YXHReadCSV2ListOneTime(this FileInfo fileInfo)
        {
            var r = await File.ReadAllLinesAsync(fileInfo.FullName);
            return r.ToList();
        }

        /// <summary>
        /// 一次性的保存成CSV
        /// </summary>
        /// <param name="filepath">保存路径</param>
        /// <param name="newlist">List数据</param>
        /// <returns></returns>
        public static async Task YXHSaveCSVfromListOneTimeAsync(this string filepath, List<string> newlist)
        {
            await File.WriteAllLinesAsync(filepath, newlist);
        }
        public static void YXHMerge(MergeClassifyModal c, string outputpath)
        {
            if (c.filelist.Count == 0)
            {
                return;
            }
            FileInfo fi = new FileInfo(outputpath);
            if (fi.Directory != null)
            {
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
            }
            if(c.filelist.Count >0)
            {
                string[] header = GetHeader(c.filelist[0].FullName);
                if (fi.Directory != null)
                {
                    if (!fi.Directory.Exists)
                    {
                        throw new Exception("无法创建日期文件夹，可能某个进程正在使用！");
                    }
                }
                using (var writer = new StreamWriter(outputpath, false, Encoding.UTF8))
                using (var csvWriter = new CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture)))
                {
                    foreach (var column in header)
                    {
                        csvWriter.WriteField(column);
                    }
                    csvWriter.NextRecord();
                    // 遍历剩余的CSV文件，写入数据行
                    for (int i = 0; i < c.filelist.Count; i++)
                    {
                        //计算前i+1个文件的总行数，这里的行数是动态计算的
                        var sumcount= c.csvrowcount.Take(i + 1).Sum();
                      
                        WriteDataBasic(c.filelist[i].FullName, csvWriter, i, c.startrowindex, c.endrowindex, c.filelist.Count, c.csvrowcount[i],sumcount);
                    }
                }
               
            }

        }
        /// <summary>
        /// 通过标题行，数据行数组和文件路径来输出csv文件
        /// </summary>
        /// <param name="data"></param>
        /// <param name="headers"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static async Task SaveCSVfromArrayData(double[][] data, string[] headers, string path)
        {
            FileInfo fi = new FileInfo(path);
            if (fi.Directory != null)
            {
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
                using (var writer = new StreamWriter(path, false, Encoding.UTF8))
                using (var csvWriter = new CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture)))
                {
                    foreach (var column in headers)
                    {
                        csvWriter.WriteField(column);
                    }
                    await csvWriter.NextRecordAsync();
                    foreach (var row in data)
                    {
                        foreach (var cell in row)
                        {
                            csvWriter.WriteField(cell);
                        }
                        await csvWriter.NextRecordAsync();
                    }
                }
            }
        }

        public static async Task SaveCSVfromListStringData(List<List<string>> data, string path)
        {
            FileInfo fi = new FileInfo(path);
            if (fi.Directory != null)
            {
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
                using (var writer = new StreamWriter(path, false, Encoding.UTF8))
                using (var csvWriter = new CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture)))
                {
                    foreach (var row in data)
                    {
                        foreach (var cell in row)
                        {
                            csvWriter.WriteField(cell);
                        }
                        await csvWriter.NextRecordAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 写入CSVI文件，分隔符为分号
        /// </summary>
        /// <param name="data"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static async Task SaveCSVIfromListStringData(List<List<string>> data, string path)
        {
            FileInfo fi = new FileInfo(path);
            if (fi.Directory != null)
            {
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
  
                using (var writer = new StreamWriter(path, false, Encoding.UTF8))
                using (var csvWriter = new CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter=";"}))
                {
                    foreach (var row in data)
                    {
                        foreach (var cell in row)
                        {
                            csvWriter.WriteField(cell);
                        }
                        await csvWriter.NextRecordAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 写入csv，数据源为类数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static async Task SaveCSVfromListTData<T> (List<T> data, string path)where T : class
        {
            if (data.Count > 0)
            {
                FileInfo fi = new FileInfo(path);
                if (fi.Directory != null)
                {
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    using (var writer = new StreamWriter(path, false, Encoding.UTF8))
                    using (var csvWriter = new CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture)))
                    {
                        await csvWriter.WriteRecordsAsync(data);
                    }
                }
            }

        }
    }
}